<template>
  <view class="address-add-container">
    <view class="form-item">
      <view class="label">选择地址:</view>
      <input v-model="newAddress.address_line1" class="selected-location" placeholder="请选择或输入地址" />
      <!-- 仅当 newAddress.address_line1 为空时显示选择地址按钮 -->
      <button v-if="!newAddress.address_line1" @click="chooseLocation">选择位置</button>
    </view>
    <view class="form-item">
      <view class="label">详细地址:</view>
      <input type="text" v-model="newAddress.address_line2" placeholder="请输入详细地址" />
    </view>
    <view class="form-item">
      <view class="label">姓名:</view>
      <input type="text" v-model="newAddress.name" placeholder="请输入姓名" />
    </view>
    <view class="form-item">
      <view class="label">电话:</view>
      <input type="text" v-model="newAddress.phone" placeholder="请输入电话" />
    </view>
    <view class="form-buttons">
      <button v-if="action === '编辑'" @click="submitAddress">保存</button>
      <button v-if="action === '编辑'" @click="deleteAddress">删除</button>
      <button v-if="action === '新增'" @click="submitAddress">完成</button>
      <button v-if="action === '新增'" @click="backaddress2">取消</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      newAddress: {
        id: '',
        name: '',
        address_line1: '',
        address_line2: '',
        phone: ''
      },
      latitude: '',
      longitude: '',
      action: '' // 用于标识是新增还是编辑
    };
  },
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('passData', (data) => {
      if (data.action === '编辑') {
        this.newAddress = JSON.parse(data.address);
        this.action = '编辑';
        this.latitude = this.newAddress.latitude; // 确保纬度和经度也被设置
        this.longitude = this.newAddress.longitude;
      } else if (data.action === '新增') {
        this.newAddress = {
          id: '',
          name: '',
          address_line1: '',
          address_line2: '',
          phone: ''
        };
        this.action = '新增';
      }
    });
  },
  onUnload() {
    // 页面卸载时移除事件监听
    this.eventChannel && this.eventChannel.off('passData');
  },
  methods: {
    chooseLocation() {
      // 检查权限
      uni.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userLocation']) {
            // 未授权，请求权限
            uni.authorize({
              scope: 'scope.userLocation',
              success: () => {
                this.getLocation();
              },
              fail: () => {
                // 用户拒绝授权，可以提示用户去设置中开启权限
                uni.openSetting({
                  success: (settingdata) => {
                    if (settingdata.authSetting['scope.userLocation']) {
                      // 用户在设置中开启了权限
                      this.getLocation();
                    } else {
                      // 用户依然没有开启权限
                      uni.showToast({
                        title: '需要位置权限',
                        icon: 'none',
                      });
                    }
                  },
                  fail: () => {
                    uni.showToast({
                      title: '获取设置失败',
                      icon: 'none',
                    });
                  }
                });
              }
            });
          } else {
            // 已授权，直接获取位置
            this.getLocation();
          }
        },
        fail: () => {
          // 获取设置失败，可能是网络问题或其他原因
          uni.showToast({
            title: '获取设置失败',
            icon: 'none',
          });
        }
      });
    },
    getLocation() {
      uni.chooseLocation({
        type: 'wgs84',
        success: (res) => {
          if (res && res.name && res.latitude && res.longitude) {
            this.newAddress.address_line1 = res.name;
            this.latitude = res.latitude;
            this.longitude = res.longitude;
          } else {
            uni.showToast({
              title: '获取位置失败，未获取到有效数据',
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '获取位置失败',
            icon: 'none',
          });
        }
      });
    },
	backaddress2(){
		uni.navigateTo({
		  url: '/pages/address/address',
		});
	},
    async submitAddress() {
      if (!this.newAddress.name || !this.newAddress.address_line2 || !this.newAddress.phone) {
        uni.showToast({
          title: '请填写所有字段',
          icon: 'none',
        });
        return;
      }
      const token = uni.getStorageSync('Authorization');
      const url = this.action === '编辑' ? 'http://localhost:8887/Useraddress/update' : 'http://localhost:8887/Useraddress/add';
      const header = {
        'Authorization': token,
        'Content-Type': 'application/json',
      };
      const res = await uni.request({
        url,
        method: 'POST',
        header,
        data: {
          ...this.newAddress,
          latitude: this.latitude,
          longitude: this.longitude
        },
      });
      if (res.data.success) {
        uni.showToast({
          title: this.action === '编辑' ? '修改成功' : '新增成功',
          icon: 'success',
        });
        uni.reLaunch({
          url: '/pages/address/address',
        });
      } else {
        uni.showToast({
          title: '操作失败',
          icon: 'none',
        });
      }
    },
    async deleteAddress() {
      const token = uni.getStorageSync('Authorization');
      const url = 'http://localhost:8887/Useraddress/deleteUser';
      const header = {
        'Authorization': token,
        'Content-Type': 'application/json',
      };
      const res = await uni.request({
        url,
        method: 'POST',
        header,
        data: {
          id: this.newAddress.id
        },
      });
      if (res.data.success) {
        uni.showToast({
          title: '删除成功',
          icon: 'success',
        });
        uni.reLaunch({
          url: '/pages/address/address',
        });
      } else {
        uni.showToast({
          title: '删除失败',
          icon: 'none',
        });
      }
    }
  },
};
</script>

<style>
.address-add-container {
  padding: 10px;
}
.form-item {
  margin-bottom: 10px;
}
.label {
  margin-bottom: 5px;
  display: block;
}
.selected-location {
  margin-top: 5px;
  font-size: 18px;
  font-weight: bold;
  color: #555;
  width: 100%;
}
.form-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
</style>